package com.xmh.myutil.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

@Slf4j
public class readJsonToSchema {

    @Test
    public void main1() {
        String path = "K:\\word_IDEA\\Template\\myutil\\src\\main\\java\\com\\xmh\\myutil\\util\\json.json";
        String fileStr = getFileStr(path);

        Map map = JSONObject.parseObject(fileStr, Map.class);

        assert map != null;

        StringBuilder sb = new StringBuilder();

        getJsonToSchema(sb, map);

        System.out.println(sb.toString());
    }

    private void getJsonToSchema(StringBuilder sb, Object object) {
        if(object == null){
            sb.append("{ \"description\":\"\",\"type\":\"string\"}");
            return;
        }

        if (object instanceof Map) {
            Map<String, Object> map = (Map) object;
            sb.append("{");
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                sb.append("\"").append(entry.getKey()).append("\":");
                getJsonToSchema(sb, entry.getValue());
                sb.append(",");
            }
            sb.replace(sb.length() - 1, sb.length(), "");
            sb.append("}");
        } else if (object instanceof List) {
            List<Object> list = (List<Object>) object;
            sb.append("{ \"description\":\"\", \"type\":\"array\",\"properties\":{");
            for (Object o : list) {
                sb.append("\"").append(o).append("\" : { \"description\":\"\",\"type\":\"string\"}");
            }
            sb.append("}");
        } else if (object instanceof String) {
            sb.append("{ \"description\":\"\",\"type\":\"string\"}");
        } else if (object instanceof Integer || object instanceof Long) {
            sb.append("{ \"description\":\"\",\"type\":\"number\"}");
        }
    }


    private String getFileStr(String path) {
        File file = new File(path);

        Reader in = null;

        String string;
        FileInputStream in2 = null;
        try {
            in2 = new FileInputStream(file);
            in = new InputStreamReader(in2, StandardCharsets.UTF_8);
            StringBuilder sBuffer = new StringBuilder();

            int len;
            while ((len = in.read()) != -1) {
                sBuffer.append((char) len);
            }
            in.close();
            string = sBuffer.toString();
        } catch (IOException e) {
            log.error("", e);
            return null;
        } finally {
            try {
                if (in2 != null) {
                    in2.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                log.error("", e);
            }
        }
        return string;
    }

}
